package com.zhiqiang.nativeplayer.frame;

import javax.swing.*;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author paul
 * @version 1.0
 * @date 18:21 2024/5/4
 * net work parts
 */
class NetWorkParts {
    
    private List<AddressPo> addressList;
    
    /** create AddressPo JComboBox */
    JComboBox<String> createAddressBox(){
        List<AddressPo> addressList = getAddressList();
        
        JComboBox<String> jcb = new JComboBox<>();
        for(AddressPo a:addressList){
            jcb.addItem(a.getHostAddress()+" "+a.getNetworkInterface().getDisplayName());
        }
        return jcb;
    }
    
    /** @param hostAddress address, may null */
    AddressPo getAddressPo(String hostAddress){
        for (AddressPo a:addressList){
            if(a.getHostAddress().equals(hostAddress)){
                return a;
            }
        }
        return null;
    }
    
    /**get address list*/
    private List<AddressPo> getAddressList(){
        addressList = new ArrayList<>();
        try {
            
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()){
               
                NetworkInterface nif = networkInterfaces.nextElement();
                List<InterfaceAddress> addresses = nif.getInterfaceAddresses();
                
                //not have address, ignore
                if(addresses.size()==0)
                    continue;
                
               
                
                //load data
                
                //get address
                for (InterfaceAddress ia :addresses
                     ) {
                    InetAddress address = ia.getAddress();
                    String hostAddress = address.getHostAddress();
                    
                    //not a site local
                    if(!address.isSiteLocalAddress()){
                        continue;
                    }
                    //nt ipv4
                    if(Pattern.matches("\\d+\\.\\d+\\.\\d+\\.\\d+",hostAddress)){
                        //log address
                        addressList.add(new AddressPo(hostAddress,address,nif));
                    }
                }
                
            }
            
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return addressList;
    }
}
